<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="code-ia4sE56m4l">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">
  
  <link rel="stylesheet" href="/blog/lib/animate-css/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css">

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"tangmonk-meat.gitee.io","root":"/blog/","scheme":"Muse","version":"8.0.0-rc.4","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"path":"search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}};
  </script>

  <meta name="description" content="疑问volatile关键字和synchronized关键字。 synchronized可以保证原子性、有序性和可见性。 而volatile却只能保证有序性和可见性。 注意：这两个有序的意思是不一样的。 那么，我们再来看一下双重校验锁实现的单例，已经使用了synchronized，为什么还需要volatile？这个volatile是否可以去掉？">
<meta property="og:type" content="article">
<meta property="og:title" content="能synchronized防止指令重排序吗？">
<meta property="og:url" content="https://tangmonk-meat.gitee.io/blog/2021/03/19/%E8%83%BDsynchronized%E9%98%B2%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F%E5%90%97%EF%BC%9F/index.html">
<meta property="og:site_name" content="唐僧肉BLOG">
<meta property="og:description" content="疑问volatile关键字和synchronized关键字。 synchronized可以保证原子性、有序性和可见性。 而volatile却只能保证有序性和可见性。 注意：这两个有序的意思是不一样的。 那么，我们再来看一下双重校验锁实现的单例，已经使用了synchronized，为什么还需要volatile？这个volatile是否可以去掉？">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-03-19T03:05:23.089Z">
<meta property="article:modified_time" content="2021-03-19T13:54:08.907Z">
<meta property="article:author" content="TANGMONK-MEAT">
<meta property="article:tag" content="java">
<meta property="article:tag" content="并发编程">
<meta property="article:tag" content="面试">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://tangmonk-meat.gitee.io/blog/2021/03/19/%E8%83%BDsynchronized%E9%98%B2%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F%E5%90%97%EF%BC%9F/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>能synchronized防止指令重排序吗？ | 唐僧肉BLOG</title>
  






  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <main class="main">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader">
        <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">唐僧肉BLOG</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">记录生活中的点点滴滴</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">44</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">17</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">38</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <section class="post-toc-wrap sidebar-panel">
          <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%96%91%E9%97%AE"><span class="nav-number">1.</span> <span class="nav-text">疑问</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#new-%E5%AF%B9%E8%B1%A1%E7%9A%84%E4%B8%89%E4%B8%AA%E6%AD%A5%E9%AA%A4%EF%BC%88%E7%AE%80%E5%8C%96%EF%BC%89"><span class="nav-number">2.</span> <span class="nav-text">new 对象的三个步骤（简化）</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%A7%A3%E5%86%B3"><span class="nav-number">3.</span> <span class="nav-text">解决</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#synchronized-%E5%92%8C-volatile%E7%9A%84%E6%9C%89%E5%BA%8F%E6%80%A7%E6%AF%94%E8%BE%83"><span class="nav-number">3.1.</span> <span class="nav-text">synchronized 和 volatile的有序性比较</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E9%99%84%E5%BD%95"><span class="nav-number">4.</span> <span class="nav-text">附录</span></a></li></ol></div>
      </section>
      <!--/noindex-->

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="TANGMONK-MEAT"
      src="https://s1.ax1x.com/2020/09/22/wOscW9.jpg">
  <p class="site-author-name" itemprop="name">TANGMONK-MEAT</p>
  <div class="site-description" itemprop="description">直到这一刻微笑着说话为止，我至少留下了一公升眼泪</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">38</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">44</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/TANGMONK-MEAT" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;TANGMONK-MEAT" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:2950371251@qq.com" title="E-Mail → mailto:2950371251@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/TANGMONK-MEAT" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;TANGMONK-MEAT" rel="noopener" target="_blank"><i class="iconfont icongitee-fill-round fa-fw"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.leancloud.cn/" title="LeanCloud → https:&#x2F;&#x2F;www.leancloud.cn" rel="noopener" target="_blank"><i class="iconfont iconCloudupload fa-fw"></i>LeanCloud</a>
      </span>
  </div>
  <div class="cc-license animated" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" class="cc-opacity" rel="noopener" target="_blank"><img src="/blog/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>



      </section>
    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </header>

      
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <a href="https://github.com/TANGMONK-MEAT" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div id="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


      <div class="main-inner">
        

        <div class="content post posts-expand">
          

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://tangmonk-meat.gitee.io/blog/2021/03/19/%E8%83%BDsynchronized%E9%98%B2%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F%E5%90%97%EF%BC%9F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="https://s1.ax1x.com/2020/09/22/wOscW9.jpg">
      <meta itemprop="name" content="TANGMONK-MEAT">
      <meta itemprop="description" content="直到这一刻微笑着说话为止，我至少留下了一公升眼泪">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="唐僧肉BLOG">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          能synchronized防止指令重排序吗？
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2021-03-19 11:05:23 / 修改时间：21:54:08" itemprop="dateCreated datePublished" datetime="2021-03-19T11:05:23+08:00">2021-03-19</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E9%9D%A2%E8%AF%95/" itemprop="url" rel="index"><span itemprop="name">面试</span></a>
                </span>
            </span>

          
            <span id="/blog/2021/03/19/%E8%83%BDsynchronized%E9%98%B2%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F%E5%90%97%EF%BC%9F/" class="post-meta-item leancloud_visitors" data-flag-title="能synchronized防止指令重排序吗？" title="阅读次数">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span class="leancloud-visitors-count"></span>
            </span>
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2021/03/19/%E8%83%BDsynchronized%E9%98%B2%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F%E5%90%97%EF%BC%9F/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2021/03/19/%E8%83%BDsynchronized%E9%98%B2%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F%E5%90%97%EF%BC%9F/" itemprop="commentCount"></span>
    </a>
  </span>
  
  <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>2k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>2 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="疑问"><a href="#疑问" class="headerlink" title="疑问"></a>疑问</h1><p><code>volatile</code>关键字和<code>synchronized</code>关键字。</p>
<p><code>synchronized</code>可以保证原子性、<strong>有序性</strong>和可见性。</p>
<p>而<code>volatile</code>却只能保证<strong>有序性</strong>和可见性。</p>
<p><strong>注意：这两个有序的意思是不一样的。</strong></p>
<p>那么，我们再来看一下<strong>双重校验锁实现的单例</strong>，已经使用了<code>synchronized</code>，为什么还需要<code>volatile</code>？这个<code>volatile</code>是否可以去掉？</p>
<a id="more"></a>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SingleInstance</span></span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 使用 volatile 禁止 new 对象时进行指令重排</span></span><br><span class="line">    <span class="comment">// new 对象，有三条指令完成</span></span><br><span class="line">    <span class="comment">// 1 JVM为对象分配一块内存M在堆区</span></span><br><span class="line">    <span class="comment">// 2 在内存M上为对象进行初始化</span></span><br><span class="line">    <span class="comment">// 3 将内存M的地址复制给instance变量</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> SingleInstance instance;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="title">SingleInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">// 反射可以直接调用构造方法，绕过private的限制</span></span><br><span class="line">        <span class="comment">// 这里进行避免</span></span><br><span class="line">        <span class="comment">// 反序列化咋搞？</span></span><br><span class="line">        <span class="keyword">if</span>(instance != <span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">&quot;single instance existed&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SingaleInstance <span class="title">getInstance</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">// 减少锁竞争，避免过多的线程进入同步队列，进入 blocking 状态</span></span><br><span class="line">        <span class="keyword">if</span>(instance == <span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="comment">// 保证只有一个线程可以实例化对象，其他线程进入同步队列blocking</span></span><br><span class="line">            <span class="comment">// 这个 syn 可以保证原子性和可见性</span></span><br><span class="line">            <span class="comment">// 而 有序性，指的是 保证线程串行进入syn 代码块内</span></span><br><span class="line">            <span class="comment">// 所以，此有序性无法保证 syn代码块 内部的有序性</span></span><br><span class="line">            <span class="keyword">synchronized</span>(SingleInstance.class)&#123;</span><br><span class="line">                <span class="comment">// 避免重复创建对象</span></span><br><span class="line">                <span class="keyword">if</span>(instance == <span class="keyword">null</span>)&#123;</span><br><span class="line">                    instance = <span class="keyword">new</span> SingleInstance();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> instance;</span><br><span class="line">    &#125;    </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由于 <code>synchronized</code> 是不能保证指令重排的，所以，可能会出问题。</p>
<h1 id="new-对象的三个步骤（简化）"><a href="#new-对象的三个步骤（简化）" class="headerlink" title="new 对象的三个步骤（简化）"></a>new 对象的三个步骤（简化）</h1><ol>
<li>JVM为对象分配一块内存M。</li>
<li>在内存M上为对象进行初始化。</li>
<li>将内存M的地址复制给singleton变量。</li>
</ol>
<p>这个步骤有两种执行顺序可以按照 ①②③或者①③②来执行。</p>
<p>当我们按照①③②的顺序来执行的时候：</p>
<p>我们假设有两个线程<strong>ThreadA</strong> 和<strong>ThreadB</strong>同时来请求<code>SingleInstance.getInstance</code>方法:</p>
<p>正常情况按照 ①②③的顺序来执行</p>
<ul>
<li><strong>ThreadA</strong> 进入到同步代码块，执行 <code>instance = new SingleInstance()</code> 进行对象的初始化（按照对象初始化的过程 ①②③）执行完。</li>
<li><strong>ThreadB</strong>进入第5行判断<code>instance</code>不为空（已经初始化好了），直接返回<code>instance</code></li>
<li>拿到这个对象做其他的操作。</li>
</ul>
<p>这样看下来是不是没有啥问题。</p>
<p>但是，如果对象初始化的时候按照 ①③② 的步骤我们再来看看：</p>
<ul>
<li><strong>ThreadA</strong>进入到同步代码块，执行 <code>instance = new SingleInstance()</code> 执行完; ①JVM为对象分配一块内存M。③将内存的地址复制给singleton变量。</li>
<li>此时<strong>ThreadB</strong>直接进入到同步代码块，发现<code>instance</code>已经不为空了然后直接就跳转到12行拿到这个<code>instance</code>返回去执行操作去了。此时ThreadB拿到的singleton对象是个半成品对象，因为还没有为这个对象进行初始化(②还没执行)。</li>
<li>所以, <strong>ThreadB</strong>拿到的对象去执行方法可能会有异常产生。至于为什么会这样列？《Java 并发编程实战》有提到</li>
</ul>
<blockquote>
<p>有 synchronized 无 volatile 的 DCL(双重检查锁) 会出现的情况：线程可能看到引用的当前值，但对象的状态值确少失效的，这意味着线程可以看到对象处于无效或错误的状态。</p>
</blockquote>
<p><strong>说白了也就是ThreadB是可以拿到一个引用已经有了但是内存资源还没有分配的对象。</strong></p>
<h1 id="解决"><a href="#解决" class="headerlink" title="解决"></a>解决</h1><blockquote>
<p>解决指令重排只要给 instance 加个<code>volatile</code>修饰就好</p>
</blockquote>
<h2 id="synchronized-和-volatile的有序性比较"><a href="#synchronized-和-volatile的有序性比较" class="headerlink" title="synchronized 和 volatile的有序性比较"></a><code>synchronized</code> 和 <code>volatile</code>的有序性比较</h2><ul>
<li><code>synchronized</code> 的有序性：是持有相同锁的两个同步块只能串行的进入，即被加锁的内容要按照顺序被多个线程执行，但是其内部的同步代码还是会发生重排序，使块与块之间有序可见。</li>
<li><code>volatile</code>的有序性：是通过插入内存屏障来保证指令按照顺序执行。不会存在后面的指令跑到前面的指令之前来执行。是保证编译器优化的时候不会让指令乱序。</li>
</ul>
<h1 id="附录"><a href="#附录" class="headerlink" title="附录"></a>附录</h1><p><a target="_blank" rel="noopener" href="https://blog.csdn.net/zengfanwei1990/article/details/110245035">https://blog.csdn.net/zengfanwei1990/article/details/110245035</a></p>

    </div>

     <!-- 文章结束表示语-->
    <div>
      
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
      
    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>TANGMONK-MEAT
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://tangmonk-meat.gitee.io/blog/2021/03/19/%E8%83%BDsynchronized%E9%98%B2%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F%E5%90%97%EF%BC%9F/" title="能synchronized防止指令重排序吗？">https://tangmonk-meat.gitee.io/blog/2021/03/19/能synchronized防止指令重排序吗？/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/zh-CN" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
              <a href="/blog/tags/%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B/" rel="tag"><i class="fa fa-tag"></i> 并发编程</a>
              <a href="/blog/tags/%E9%9D%A2%E8%AF%95/" rel="tag"><i class="fa fa-tag"></i> 面试</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2021/03/16/%E4%BB%80%E4%B9%88%E6%98%AF%E7%BA%BF%E7%A8%8B%E5%AE%89%E5%85%A8/" rel="prev" title="什么是线程安全？">
      <i class="fa fa-chevron-left"></i> 什么是线程安全？
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2021/03/19/NoClassDefFoundError:%20org.openjdk.jol.info.ClassLayout/" rel="next" title="NoClassDefFoundError:org.openjdk.jol.info.ClassLayout">
      NoClassDefFoundError:org.openjdk.jol.info.ClassLayout <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



        </div>
        
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">TANGMONK-MEAT</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">148k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">2:15</span>
</div>

<!--
-->

<!--<div>
<span id="busuanzi_container_site_pv">
    本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span> 
 <span class="post-meta-divider">|</span> 
 <span class="post-meta-item-icon">
<span id="busuanzi_container_site_uv">
  本站访客数<span id="busuanzi_value_site_uv"></span>人次
</span>
</div> 

-->




        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/muse.js"></script>


<script src="/blog/js/next-boot.js"></script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/blog/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments('#valine-comments', () => {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', () => {
    new Valine(Object.assign({
      el  : '#valine-comments',
      path: location.pathname,
    }, {"enable":true,"appId":"dkMV7sEQR97E6CWI5jduGKf3-gzGzoHsz","appKey":"JQfXJ0ELtfNma5bdMQk0vgwX","placeholder":"ヾﾉ≧∀≦)o来啊，快活啊!","avatar":"mm","meta":["nick","mail"],"pageSize":10,"language":"zh-cn","visitor":true,"comment_count":true,"recordIP":true,"serverURLs":null,"enableQQ":false,"requiredFields":[]}
    ));
  }, window.Valine);
});
</script>

</body>
</html>
